package api

import (
	"certificate-manager/pkg/app"
	"certificate-manager/pkg/constant"
	"certificate-manager/pkg/e"
	"certificate-manager/pkg/log"
	"certificate-manager/pkg/utils"
	v1 "certificate-manager/routers/api/v1"
	"certificate-manager/thirdparty/redisc"
	"fmt"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// AddDomain 手动添加受监测域名
func AddDomain(c *gin.Context) {
	appG := app.Gin{C: c}
	valid := validation.Validation{}

	var domainVo v1.DomainVo
	err := c.ShouldBind(&domainVo)
	if err != nil {
		log.Logger.Error("【AddDomain】param error.", zap.Any("err", fmt.Errorf("param error")), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.InvalidParams, nil)
		return
	}

	ok, _ := valid.Valid(&domainVo)
	if !ok {
		log.Logger.Error("【AddDomain】param error.", zap.Any("err", fmt.Errorf("param error")), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.InvalidParams, nil)
		return
	}

	//1、获取新的dn
	key := domainVo.Key
	dn := domainVo.Dn

	redisKey := "ssl:dn:" + key

	//2、判断Redis中是否存在
	redisClient, err := redisc.GetRedisClientInstance()
	if err != nil {
		log.Logger.Error("【AddDomain】failed create new redis client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.RedisError, nil)
		return
	}

	exists, err := redisClient.IsRedisKeyExists(redisKey)
	if err != nil {
		log.Logger.Error("【AddDomain】failed call exist from redis client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.RedisError, nil)
		return
	}

	if exists == 1 {
		log.Logger.Info("【AddDomain】domain already existed.", zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.DomainHasAlreadyExisted, nil)
		return
	}

	//添加domain
	fields := map[string]interface{}{
		constant.DomainKey: dn,
	}

	err = redisClient.WriteRedisHashKeys(redisKey, fields)
	if err != nil {
		log.Logger.Error("【AddDomain】failed call hset from redis client.", zap.Any("err", err), zap.Any("func", utils.RunFuncName()))
		appG.Response(http.StatusOK, e.RedisError, nil)
	}

	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"msg": "写入成功",
	})
}
